package com.zjitc.backend_shop.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.ExpiredJwtException;

import java.security.Key;
import java.util.Date;

public class JwtUtils {

    private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    private static final long EXPIRATION_TIME = 3600000; // 1 hour

    public static String generateToken(String subject) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 设置Token过期时间
        long expMillis = nowMillis + EXPIRATION_TIME;
        Date exp = new Date(expMillis);

        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(exp)
                .signWith(key)
                .compact();
    }

    public static Claims validateToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (SignatureException e) {
            // 处理签名不匹配的异常
            System.out.println("无效的JWT签名: " + e.getMessage());
            return null; // 或者根据需要返回其他值
        } catch (ExpiredJwtException e) {
            // 处理过期的token
            System.out.println("JWT已过期: " + e.getMessage());
            return null; // 或者根据需要返回其他值
        } catch (Exception e) {
            // 处理其他可能的异常
            System.out.println("JWT验证失败: " + e.getMessage());
            return null; // 或者根据需要返回其他值
        }
    }
}
